/*
  Name: CDatabase
  Copyright: http://www.dreamincode.net/forums/topic/122300-sqlite-in-c/
  Author: TyVeryMuch
  Date: 02.10.11 16:42
  Description: connector for SQLite3 database
*/

#include "database.h"
#include <iostream>
#include <assert.h>
	 
CDatabase::CDatabase(const string filename)	{
	database = NULL;
	if (open(filename) == false)
		throw dbErr();
}

CDatabase::~CDatabase()	{
	return;
}

bool CDatabase::open(const string filename)	{
	if(sqlite3_open(filename.c_str(), &database) == SQLITE_OK)
		return true;
	else
		return false;  
}

vector<vector<string> > CDatabase::query(const string query) {
	sqlite3_stmt *statement;
	vector<vector<string> > results;
	 
	if(sqlite3_prepare_v2(database, query.c_str(), -1, &statement, 0) == SQLITE_OK) {
		int cols = sqlite3_column_count(statement);
		int result = 0;
		while(true) {
			result = sqlite3_step(statement);

            if(result == SQLITE_ROW) {
				vector<string> values;
				for(int col = 0; col < cols; col++) {
					values.push_back((char*)sqlite3_column_text(statement, col));
				}
				results.push_back(values);
			} else
				break;  
		}
	        
		sqlite3_finalize(statement);
	}

	string error = sqlite3_errmsg(database);
	if(error != "not an error")
		cout << query << " " << error << endl;

	return results; 
}

void CDatabase::close()	{

	sqlite3_close(database);  
}
